#!/usr/bin/env bash
set +e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <projects_list_file> <ossfuzz_dir>"
    exit 1
fi

PROJECTS_LIST=$1
OSSFUZZ_DIR=$2

# 从 cprojects.list 里提取项目名（去掉前面的数字和 .info 后缀）
get_project_name() {
    local line="$1"
    local name=$(basename "$line")
    name="${name%.info}"      # 去掉 .info
    name="${name#[0-9][0-9][0-9]-}"  # 去掉前面的编号
    echo "$name"
}

# 重试函数
run_with_retry_or_skip() {
    local cmd=("$@")
    local attempt=1
    local MAX_RETRIES=3
    while [ $attempt -le $MAX_RETRIES ]; do
        echo "[INFO] Attempt $attempt: ${cmd[*]}"
        if "${cmd[@]}"; then
            return 0
        else
            echo "[WARN] Attempt $attempt failed."
            ((attempt++))
        sleep 5
        fi
    done
    echo "[ERROR] All $MAX_RETRIES attempts failed: ${cmd[*]}"
    return 1
}

FAILED_LOG="$OSSFUZZ_DIR/failed_builds.log"

while IFS= read -r line || [ -n "$line" ]; do
    proj=$(get_project_name "$line")
    echo "[BUILD] Building project: $proj"
    # 构建镜像，失败重试
    if ! run_with_retry_or_skip bash -c "yes y | python3 infra/helper.py build_image $proj"; then
        echo "[ERROR] Skipping project $proj due to build_image failure."
        continue
    fi

    # 构建 fuzzers，失败重试
    {
        OUTPUT=$(run_with_retry_or_skip bash -c "yes y | python3 infra/helper.py build_fuzzers $proj --engine libfuzzer --sanitizer address" 2>&1)
    } >/dev/null 2>&1

    if [ $? -ne 0 ]; then
        echo "[ERROR] Skipping project $proj due to build_fuzzers failure."
        echo "$(date '+%Y-%m-%d %H:%M:%S') | $proj | build_fuzzers failed" >> "$FAILED_LOG"
        echo "---- error log ----" >> "$FAILED_LOG"
        echo "$OUTPUT" >> "$FAILED_LOG"
        echo "-------------------" >> "$FAILED_LOG"
        continue
    fi

    # 创建输出挂载目录
    OUT_DIR="$OSSFUZZ_DIR/projects/$proj/out"
    mkdir -p "$OUT_DIR"

    # 将容器 /out 挂载到宿主机 OUT_DIR
    IMAGE_NAME="gcr.io/oss-fuzz/$proj"
    CONTAINER_NAME="${proj}_build"

    docker create --name "$CONTAINER_NAME" "$IMAGE_NAME"
    docker cp "$CONTAINER_NAME":/src/"$proj"/. ./projects/"$proj"/out
    python3 analyze_projects.py --in /root/gyx/oss-fuzz/projects/"$proj"/out --out ossfuzz_full_scan.csv

    docker rm "$CONTAINER_NAME"
    docker rmi "$IMAGE_NAME"
    yes y | docker container prune
    yes y | docker image prune
    rm -rf ./projects/"$proj"/out

    # 从项目列表中删除已处理的项目
    sed -i "\|$line|d" "$PROJECTS_LIST"

done < "$PROJECTS_LIST"
